import jq from 'jquery'

const KEY_CODE = {
    ESC: 27,
    TAB: 9,
    ENTER: 13,
    CTRL: 17,
    A: 65,
    P: 80,
    N: 78,
    LEFT: 37,
    UP: 38,
    RIGHT: 39,
    DOWN: 40,
    BACKSPACE: 8,
    SPACE: 32,
    // 50可能是2或@
    AT:50
};

//输入框获取光标
const getPosition = function (textarea) {
    // 光标位置
    let end = textarea.selectionEnd;
    // 光标前的内容
    let beforeText = textarea.value.slice(0, end);
    // 光标后的内容
    let afterText = textarea.value.slice(end);
    // 对影响 UI 的特殊元素编码
    let escape = function(text) {
        return text.replace(/<|>|`|"|&/g, '?').replace(/\r\n|\r|\n/g, '<br>')
    }

    // 创建镜像内容，复制样式
    let mirror = '<div class="textarea-mirror">'
        + escape(beforeText)
        + '<span id="cursor">|</span>'
        + escape(afterText)
        + '</div>';
    // 添加到 textarea 同级，注意设置定位及 zIndex，使两个元素重合
    let jqmir = jq(mirror);
    let jqtext = jq(textarea);
    jqtext.after(jqmir)
    // 通过镜像元素中的假光标占位元素获取像素位置
    let cursor = document.getElementById('cursor');
    let rect = cursor.getBoundingClientRect()  // { width, height, top, right, bottom, right }
    let x = rect.left;
    let y = rect.top - jqtext.outerHeight(true) + 7;
    jqmir.remove();
    return {x:x, y:y}
}

class Atwho{
    constructor(options = {}) {
        Object.assign(this, {
            altflg : false,
            nameMap : {}
        }, options);
        this.jqElement = jq(this.element);
        this.creatSelUserTab(this.comments);
        this.init();
    }
    creatSelUserTab(comments) {
        if (comments == "undefined" || !comments) {
            return;
        }
        let outdiv = jq("<div class='giteement-at-outdiv'></div>");
        let atdiv = jq("<div class='giteement-at-div'></div>");
        let ol = jq("<ol class='giteement-at-ol'></ol>")

        let tmp = {}
        for (let i = 0 ; i < comments.length; i++) {
            let user = comments[i].user;
            this.nameMap[user.name] = user.login;
            if (tmp[user.login]) {
                continue;
            }
            tmp[user.login] = user.name;
            let li;
            if (i === (comments.length - 1)) {
                li = jq("<li class='giteement-at-li giteement-at-li-tail'></li>");
            } else {
                li = jq("<li class='giteement-at-li'></li>");
            }
            li.text(user.login + "  " + user.name);
            ol.append(li);
        }
        atdiv.append(ol);
        outdiv.append(atdiv)
        jq(this.container).append(outdiv);
        jq(document).off("keydown.atwhouser").on("keydown.atwhouser" , function(e){
            if (KEY_CODE.DOWN === e.keyCode) {
                let next = jq(".giteement-at-li-select").next();
                jq(".giteement-at-li-select").removeClass("giteement-at-li-select");
                if (next.length == 0) {
                    jq(".giteement-at-li:first").addClass("giteement-at-li-select");
                } else {
                    next.addClass("giteement-at-li-select");
                }

            } else if (KEY_CODE.UP === e.keyCode) {
                let pre = jq(".giteement-at-li-select").prev();
                jq(".giteement-at-li-select").removeClass("giteement-at-li-select");
                if (pre.length == 0) {
                    jq(".giteement-at-li:last").addClass("giteement-at-li-select");
                } else {
                    pre.addClass("giteement-at-li-select");
                }
            }
        })
    }
    init() {
        this.addListener();
    }
    addListener() {
        let that = this;
        that.jqElement.on('compositionstart', function () {
            console.log("---compositionstart");
        }).on('compositionend', function () {
            console.log("---compositionend");
        }).on('keyup.atwhoInner', function (e) {

            that.onKeyup(e);
        }).on('keydown.atwhoInner', function (e) {
            if (that.altflg) {
                if (KEY_CODE.UP === e.keyCode
                    || KEY_CODE.DOWN === e.keyCode || KEY_CODE.ENTER === e.keyCode) {
                    e.preventDefault();
                }
            }
            that.onKeydown(e);
        }).on('blur.atwhoInner', function () {
            jq(".giteement-at-div").hide();
            this.altflg = false;
        }).on('click.atwhoInner', function () {
            console.log("---click.atwhoInner");
        }).on('scroll.atwhoInner', function () {
            console.log("---scroll.atwhoInner");
        });
    }
    onKeyup(el) {
        let flg = this.jqElement.val().substring(0, this.jqElement[0].selectionEnd);
        // if (KEY_CODE.AT === el.keyCode) {
        //     jq(".giteement-at-div").hide();
        //     this.altflg = false;
        // }

        if ("@" === flg) {
            if (this.altflg) {
                if (KEY_CODE.ENTER === el.keyCode) {
                    let selUser = jq(".giteement-at-li-select").text().split("  ");
                    let seltext = selUser[1] + " ";
                    this.jqElement[0].setRangeText(seltext);
                    this.jqElement[0].selectionStart = this.jqElement[0].selectionEnd = this.jqElement.val().length;
                    jq(".giteement-at-div").hide();
                    this.altflg = false;
                }
                return;
            }
            let pos = getPosition(this.jqElement[0]);
            let outrect = jq(".giteement-at-outdiv")[0].getBoundingClientRect();
            jq(".giteement-at-div").css("left", pos.x - outrect.left  + "px");
            jq(".giteement-at-div").css("top", pos.y  - outrect.top + "px");
            jq(".giteement-at-li-select").removeClass("giteement-at-li-select");
            jq(jq(".giteement-at-li")[0]).addClass("giteement-at-li-select");
            jq(".giteement-at-div").show();
            this.altflg = true;
        } else {
            jq(".giteement-at-div").hide();
            this.altflg = false;
        }
        
        // if (KEY_CODE.AT === el.keyCode) {
        //
        // } else {
        //     if (this.altflg && (KEY_CODE.UP === el.keyCode || KEY_CODE.DOWN === el.keyCode)) {
        //         return
        //     }
        //     jq(".giteement-at-div").hide();
        //     this.altflg = false;
        // }
    }
    onKeydown(el) {
        if (this.altflg) {
            if (KEY_CODE.UP === el.keyCode
                || KEY_CODE.DOWN === el.keyCode || KEY_CODE.ENTER === el.keyCode) {
                el.preventDefault();
            }
        }
    }
}

module.exports = Atwho